<template>
  <el-dialog
    :title="`${isCreate ? '添加' : '编辑'}轮播图`"
    :visible.sync="dialogVisible"
    class="dialog"
    width="500px">
    <el-form
      :model="formData"
      label-width="120px"
      ref="form"
      size="small">
      <el-form-item label="链接课程" prop="courseId">
        <el-select
          filterable
          remote
          :remote-method="getCourseList"
          v-model="formData.courseId"
          placeholder="搜索课程">
          <el-option
            v-for="item in courseList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图标" prop="imgUrl">
        <uploader :src.sync="formData.imgUrl"></uploader>
      </el-form-item>
    </el-form>
    <dialog-footer
      slot="footer"
      @cancel="dialogVisible = false"
      @confirm="confirm"
    />
  </el-dialog>
</template>
<script>
import { updateBanner, saveBanner } from '@/api/base-config';
import { getCourseList } from '@/api/course';

export default {
  props: {
    initFormData: Object,
    isCreate: Boolean,
  },
  data() {
    return {
      formData: {
        ...this.initFormData,
      },
      dialogVisible: false,
      courseList: [],
    };
  },
  watch: {
    initFormData(val) {
      this.formData = { ...val };
    },
    dialogVisible(val) {
      if (!this.isCreate && val) {
        this.courseList = [
          {
            value: this.formData.courseId,
            label: this.formData.name,
          },
        ];
      } else {
        this.courseList = [];
      }
    },
  },
  methods: {
    async confirm() {
      const { courseId, imgUrl } = this.formData;
      if (courseId && imgUrl) {
        if (this.isCreate) {
          await saveBanner({
            ...this.formData,
            name: 'banner',
          });
        } else {
          await updateBanner({
            ...this.formData,
            name: 'banner',
          });
        }
        this.dialogVisible = false;
        this.$emit('confirm');
      } else {
        this.$message.error('链接课程和图标不能为空');
      }
    },
    async getCourseList(query) {
      if (query) {
        const { list } = await getCourseList({
          name: query,
          pageSize: 50,
          pageNum: 0,
          valid: 1,
        });
        this.courseList = list.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      } else {
        this.courseList = [];
      }
    },
  },
};
</script>
<style lang="scss" scoped>
  .dialog {
    ::v-deep .el-input__inner {
      width: 200px;
    }
  }
</style>
